<template>
  <div class="order-management">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-input
        v-model="searchText"
        placeholder="搜索订单号/表白人/礼物类型"
        style="width: 360px"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增订单
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table 
      :data="filteredOrders" 
      border 
      style="width: 100%"
      header-row-class-name="table-header"
      stripe
      highlight-current-row
    >
      <el-table-column prop="orderId" label="订单号" width="180" sortable align="center" />
      <el-table-column prop="sender" label="表白人" width="120" />
      <el-table-column prop="giftType" label="礼物类型" width="140">
        <template #default="{ row }">
          <el-tag effect="plain" :type="giftTagType[row.giftType]">
            {{ row.giftType }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="receiver" label="收礼人" width="150" />
      <el-table-column prop="amount" label="礼物金额" width="120" align="center">
        <template #default="{ row }">
          <span style="color: #d63384;">¥{{ row.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="paymentStatus" label="支付状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="paymentTagType[row.paymentStatus]" effect="light">
            {{ paymentOptions.find(s => s.value === row.paymentStatus)?.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="deliveryStatus" label="礼物状态" width="120" align="center">
        <template #default="{ row }">
          <el-tag :type="deliveryTagType[row.deliveryStatus]" effect="light">
            {{ deliveryOptions.find(s => s.value === row.deliveryStatus)?.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="message" label="情书内容" width="160">
        <template #default="{ row }">
          <div class="message-preview">{{ row.message }}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="{ row }">
          <el-button size="small" type="primary" plain @click="handleEdit(row)">编辑</el-button>
          <el-button
            size="small"
            type="danger"
            plain
            @click="handleDelete(row.orderId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑订单信息' : '新增表白订单'"
      width="680"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="订单号" prop="orderId">
          <el-input 
            v-model="formData.orderId" 
            :disabled="isEditMode"
            placeholder="GF开头+8位日期+3位序列"
          />
        </el-form-item>
        <el-form-item label="表白人" prop="sender">
          <el-input v-model="formData.sender" placeholder="请输入您的姓名"/>
        </el-form-item>
        <el-form-item label="礼物类型" prop="giftType">
          <el-select 
            v-model="formData.giftType"
            placeholder="请选择礼物类型"
            style="width: 100%"
          >
            <el-option
              v-for="item in giftTypes"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="收礼人" prop="receiver">
          <el-input 
            v-model="formData.receiver"
            placeholder="请输入对方姓名"
          />
        </el-form-item>
        <el-form-item label="礼物金额" prop="amount">
          <el-input-number
            v-model="formData.amount"
            :min="0"
            :precision="2"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="支付状态" prop="paymentStatus">
          <el-select 
            v-model="formData.paymentStatus"
            placeholder="请选择支付状态"
            style="width: 100%"
          >
            <el-option
              v-for="item in paymentOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="礼物状态" prop="deliveryStatus">
          <el-select 
            v-model="formData.deliveryStatus"
            placeholder="请选择当前状态"
            style="width: 100%"
          >
            <el-option
              v-for="item in deliveryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="情书内容" prop="message">
          <el-input 
            type="textarea"
            v-model="formData.message" 
            placeholder="写下您的心意（支持emoji）"
            :rows="3"
            show-word-limit
            maxlength="100"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 礼物类型配置
const giftTypes = [
  '鲜花礼盒',
  '创意首饰',
  '手工巧克力',
  '情侣对戒',
  '星空投影',
  '定制玩偶'
]

// 标签样式映射
const giftTagType = {
  '鲜花礼盒': 'danger',
  '创意首饰': 'warning',
  '手工巧克力': 'info',
  '情侣对戒': 'primary',
  '星空投影': 'success',
  '定制玩偶': ''
}

// 支付状态选项
const paymentOptions = [
  { value: 'unpaid', label: '待支付' },
  { value: 'paid', label: '已支付' },
  { value: 'refunded', label: '已退款' }
]

const paymentTagType = {
  'unpaid': 'warning',
  'paid': 'success',
  'refunded': 'danger'
}

// 礼物状态选项
const deliveryOptions = [
  { value: 'pending', label: '待处理' },
  { value: 'preparing', label: '准备中' },
  { value: 'delivering', label: '配送中' },
  { value: 'completed', label: '已签收' }
]

const deliveryTagType = {
  'pending': 'info',
  'preparing': 'primary',
  'delivering': 'warning',
  'completed': 'success'
}

// 初始订单数据（10条）
const orders = ref([
  {
    orderId: 'GF20240520001',
    sender: '张小凡',
    giftType: '鲜花礼盒',
    receiver: '陆雪琪',
    amount: 520.0,
    paymentStatus: 'paid',
    deliveryStatus: 'completed',
    message: '这束玫瑰就像你的笑容，永远绽放在我心中🌹'
  },
  {
    orderId: 'GF20240520002',
    sender: '李逍遥',
    giftType: '情侣对戒',
    receiver: '赵灵儿',
    amount: 1314.0,
    paymentStatus: 'paid',
    deliveryStatus: 'delivering',
    message: '愿这对戒指见证我们永恒的约定💍'
  },
  {
    orderId: 'GF20240520003',
    sender: '匿名',
    giftType: '手工巧克力',
    receiver: '苏同学',
    amount: 199.0,
    paymentStatus: 'unpaid',
    deliveryStatus: 'pending',
    message: '每天一颗巧克力，甜进你的心里❤️'
  },
  {
    orderId: 'GF20240520004',
    sender: '王小明',
    giftType: '星空投影',
    receiver: '林月如',
    amount: 399.0,
    paymentStatus: 'paid',
    deliveryStatus: 'preparing',
    message: '想把整片星空都送给你，就像你照亮我的世界✨'
  },
  {
    orderId: 'GF20240520005',
    sender: '赵灵儿',
    giftType: '定制玩偶',
    receiver: '李逍遥',
    amount: 299.0,
    paymentStatus: 'refunded',
    deliveryStatus: 'completed',
    message: '这个小灵儿会永远陪着你哦~'
  },
  {
    orderId: 'GF20240520006',
    sender: '叶修',
    giftType: '创意首饰',
    receiver: '苏沐橙',
    amount: 888.0,
    paymentStatus: 'paid',
    deliveryStatus: 'delivering',
    message: '这条项链和你一样闪耀💎'
  },
  {
    orderId: 'GF20240520007',
    sender: '楚子航',
    giftType: '手工巧克力',
    receiver: '夏弥',
    amount: 199.0,
    paymentStatus: 'paid',
    deliveryStatus: 'preparing',
    message: '每一颗都是亲手制作的心意🍫'
  },
  {
    orderId: 'GF20240520008',
    sender: '路明非',
    giftType: '星空投影',
    receiver: '诺诺',
    amount: 399.0,
    paymentStatus: 'unpaid',
    deliveryStatus: 'pending',
    message: '希望你能喜欢这片只属于你的星空🌌'
  },
  {
    orderId: 'GF20240520009',
    sender: '萧炎',
    giftType: '创意首饰',
    receiver: '薰儿',
    amount: 999.0,
    paymentStatus: 'paid',
    deliveryStatus: 'completed',
    message: '此物配你，方显绝世风华'
  },
  {
    orderId: 'GF20240520010',
    sender: '唐三',
    giftType: '定制玩偶',
    receiver: '小舞',
    amount: 299.0,
    paymentStatus: 'paid',
    deliveryStatus: 'delivering',
    message: '让它代替我时刻陪伴你👫'
  }
])

// 搜索功能
const searchText = ref('')
const filteredOrders = computed(() => {
  return orders.value.filter(order => {
    return Object.values(order).some(value => 
      String(value).toLowerCase().includes(searchText.value.toLowerCase())
  )})
})

// 对话框相关状态
const dialogVisible = ref(false)
const isEditMode = ref(false)
const formRef = ref(null)
const formData = reactive({
  orderId: '',
  sender: '',
  giftType: '',
  receiver: '',
  amount: 0,
  paymentStatus: 'unpaid',
  deliveryStatus: 'pending',
  message: ''
})

// 表单验证规则
const formRules = {
  orderId: [
    { required: true, message: '请输入订单号', trigger: 'blur' },
    { pattern: /^GF\d{8}\d{3}$/, message: '格式要求：GF+8位日期+3位序列', trigger: 'blur' }
  ],
  sender: [
    { required: true, message: '请输入您的姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
  ],
  giftType: { required: true, message: '请选择礼物类型', trigger: 'change' },
  receiver: [
    { required: true, message: '请输入对方姓名', trigger: 'blur' }
  ],
  amount: [
    { required: true, message: '请输入礼物金额', trigger: 'blur' },
    { type: 'number', min: 0, max: 9999, message: '金额范围0-9999元', trigger: 'blur' }
  ]
}

// 操作函数
const handleAdd = () => {
  isEditMode.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEditMode.value = true
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

const handleDelete = (orderId) => {
  ElMessageBox.confirm('确定要删除该订单吗？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    orders.value = orders.value.filter(u => u.orderId !== orderId)
    ElMessage.success('删除成功')
  })
}

const submitForm = async () => {
  await formRef.value.validate()
  if (isEditMode.value) {
    const index = orders.value.findIndex(u => u.orderId === formData.orderId)
    orders.value.splice(index, 1, { ...formData })
  } else {
    if (orders.value.some(u => u.orderId === formData.orderId)) {
      return ElMessage.warning('订单号已存在')
    }
    orders.value.push({ ...formData })
  }
  dialogVisible.value = false
  ElMessage.success(isEditMode.value ? '修改成功' : '新增成功')
}

const resetForm = () => {
  formData.orderId = ''
  formData.sender = ''
  formData.giftType = ''
  formData.receiver = ''
  formData.amount = 0
  formData.paymentStatus = 'unpaid'
  formData.deliveryStatus = 'pending'
  formData.message = ''
}
</script>

<style scoped lang="scss">
.order-management {
  padding: 24px;
  background: #fff5f7;
  min-height: 100vh;

  .operation-bar {
    padding: 16px 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(214,51,132,0.08);
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    gap: 16px;
  }

  :deep(.table-header) th {
    background-color: #fff5f7 !important;
    color: #d63384;
    font-weight: 600;
    height: 56px;
  }

  .el-table {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(214,51,132,0.08);
    
    .el-tag {
      font-size: 13px;
      padding: 0 8px;
      height: 26px;
      line-height: 24px;
    }
  }

  .message-preview {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    line-height: 1.5;
    color: #6b1b7a;
  }
}

.el-dialog {
  border-radius: 12px;
  
  .el-dialog__header {
    border-bottom: 1px solid #ffd6e6;
    margin: 0 24px;
    padding: 24px 0 16px;
  }
  
  .el-dialog__body {
    padding: 24px 32px;
  }
  
  .el-dialog__footer {
    border-top: 1px solid #ffd6e6;
    padding: 16px 24px;
  }
}

.el-form-item {
  margin-bottom: 20px;
}
</style>